<template>
  <div class="container">
        <div class="handle-box">
                <el-form ref="form" :model="form" label-width="80px" class="flex">
                    <el-form-item label="名称：">
                        <el-input v-model="name" placeholder="请输入名称" class="handle-input mr10" @input="mohu()"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" >搜索</el-button>
                        <el-button type="success" icon="el-icon-circle-plus-outline" @click="addvialog()">新增</el-button>
                    </el-form-item>
                    <el-upload
                      action="/上传文件的接口"
                      :on-change="onChange"
                      :auto-upload="false"
                      :show-file-list="false"
                      accept=".xls, .xlsx"  class="upload">
                      <el-button type="warning" icon="el-icon-folder-add" style="width:97px;height:33px">批量导入</el-button>
                    </el-upload>
                    <el-button type="error" icon="el-icon-download" @click="exportToExcel">批量导出</el-button>
                </el-form>
        </div>
    
         <el-table
          :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
          border
          style="width: 100%">
          <el-table-column prop="ID" label="id" ></el-table-column>
          <el-table-column prop="VILLAGE_NO" label="小区名称" ></el-table-column>
          <el-table-column prop="NAME" label="名字"></el-table-column>
          <el-table-column prop="AREA" label="区域"></el-table-column>
          <el-table-column prop="LONGITUDE" label="经度"></el-table-column>
          <el-table-column prop="LATITUDE" label="纬度"></el-table-column>
          <el-table-column prop="LOCATION" label="位置"></el-table-column>
          <el-table-column prop="TYPE" label="类型"></el-table-column>
          <el-table-column prop="SIZE" label="重量"></el-table-column>
          <el-table-column prop="PHOTO" label="图片"></el-table-column>
          <el-table-column prop="REMARK" label="备注"></el-table-column>
          <el-table-column fixed="right" label="操作" width="200">
            <template slot-scope="scope">
              <!-- <el-button @click="handleClick(scope.row)" type="text" size="small" style="color:blue">查看</el-button> -->
              <el-button type="text" size="small" @click="handleEdit(scope.$index,scope.row)" >编辑</el-button>
              <el-button type="text" size="small" @click="handleDelete(scope.row,scope.$index)"  style="color:red">删除</el-button>
              <el-button type="text" size="small" @click="handledIstribution(scope.row,scope.$index)"  style="color:#2189FF">分配</el-button>
            </template>
          </el-table-column>
        </el-table>
    <div class="pagination">
                <el-pagination
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :current-page="currentPage"  
                    :page-size="pageSize"
                    :total="tableData.length"
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
  <el-dialog v-dialogDrag title="新增" :visible.sync="addeditVisible" width="40%">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="flex">
        <el-form-item label="名称：" prop="NAME" class="wid50">
            <el-input v-model="ruleForm.NAME" ></el-input>
        </el-form-item>
         <el-form-item label="地区："  class="wid50">
            <el-select v-model="ruleForm.REGION_ID" placeholder="请选择地区"  @change="changevalue">
                <el-option v-for="item in option" :key="item.REGION_ID" :label="item.REGION_NAME" :value="item.REGION_ID" ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="街道：" class="wid50">
            <el-select v-model="ruleForm.STREET_ID" placeholder="请选择街道"  @change="changecommunitvalue">
              <el-option v-for="item in optionsstreet" :key='item.STREET_ID' :label="item.STREET_NAME" :value="item.STREET_ID">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="社区：" class="wid50">
            <el-select v-model="ruleForm.COMMUNITY_ID" placeholder="请选择"   @change="changeplot">
              <el-option v-for="item in optionscommunit" :key='item.COMMUNITY_ID' :label="item.COMMUNITY_NAME" :value="item.COMMUNITY_ID">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="小区："  class="wid50">
            <el-select v-model="ruleForm.VILLAGE_ID" placeholder="请选择" >
              <el-option v-for="item in optionsplot" :key='item.VILLAGE_ID' :label="item.VILLAGE_NAME" :value="item.VILLAGE_ID">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="经度：" prop="LONGITUDE" class="wid50">
            <el-input v-model="ruleForm.LONGITUDE" ></el-input>
        </el-form-item>
        <el-form-item label="纬度：" prop="LATITUDE" class="wid50">
            <el-input v-model="ruleForm.LATITUDE" ></el-input>
        </el-form-item>
        <el-form-item label="位置：" prop="LOCATION" class="wid50">
            <el-input v-model="ruleForm.LOCATION" ></el-input>
        </el-form-item>
        <el-form-item label="类型：" prop="SIZE" class="wid50">
            <el-input v-model="ruleForm.SIZE" ></el-input>
        </el-form-item>
        <!-- <el-form-item label="图片：" prop="PHOTO" class="wid50">
            <el-input v-model="ruleForm.PHOTO" ></el-input>
        </el-form-item> -->
        <el-form-item width="200" align="center" label="图片：" prop="PHOTO">
          <!-- <input  accept="image/gif,image/jpeg,image/jpg,image/png" type="file" id="up" /> -->
          <!-- <input type="file" ref="file2" name="check_img_url" @change="tirggerFile($event)" />
           -->
            <!-- <input class="crop-input" name="file" type="file" accept="image/png,image/gif,image/jpeg" @change="update"/> -->
             <el-upload
              ref="imgBroadcastUpload"
              :auto-upload="false" multiple
              :file-list="diaLogForm.imgBroadcastList"
              list-type="picture-card"
              :on-change="imgBroadcastChange"
              :on-remove="imgBroadcastRemove"
              accept="image/jpg,image/png,image/jpeg"
              action="">
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
             </el-upload>
        </el-form-item>
        <!-- <el-form-item label="备注：" prop="" class="wid50">
            <el-input v-model="ruleForm." ></el-input>
        </el-form-item> -->
        <!-- <el-form-item label="图片" ref="uploadElement" prop="photo">
            <el-input v-model="ruleForm.photo" v-if="false"></el-input>
            <el-upload
                    class="avatar-uploader"
                    ref="upload"
                    :show-file-list="false"
                    action="/index/upload"
                    :before-upload="beforeUpload"
                    :on-change="handleChange"
                    :auto-upload="false"
                    :data="ruleForm">
                <img v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item> -->
        <el-form-item style="margin:0 auto">
            <el-button type="primary" @click="addForms(ruleForm)">确定</el-button>
            <el-button @click="resetForm()">取消</el-button>
        </el-form-item>
    </el-form>
  </el-dialog>
  <!-- 编辑 -->
  <el-dialog v-dialogDrag title="编辑" :visible.sync="editVisible" width="40%">
    <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px" class="flex">
       <el-form-item label="名称" prop="NAME" class="wid50">
            <el-input v-model="editForm.NAME" ></el-input>
        </el-form-item>
        <el-form-item label="区域" prop="AREA" class="wid50">
            <!-- <el-input v-model="editForm.AREA" ></el-input> -->
          
        </el-form-item>
        <el-form-item label="经度：" prop="LONGITUDE" class="wid50">
            <el-input v-model="editForm.LONGITUDE" ></el-input>
        </el-form-item>
        <el-form-item label="纬度：" prop="LATITUDE" class="wid50">
            <el-input v-model="editForm.LATITUDE" ></el-input>
        </el-form-item>
        <el-form-item label="位置：" prop="LOCATION" class="wid50">
            <el-input v-model="editForm.LOCATION" ></el-input>
        </el-form-item>
        <el-form-item label="类型：" prop="SIZE" class="wid50">
            <el-input v-model="editForm.SIZE" ></el-input>
        </el-form-item>
        <!-- <el-form-item label="图片" ref="uploadElement" prop="photo">
            <el-input v-model="ruleForm.photo" v-if="false"></el-input>
            <el-upload
                    class="avatar-uploader"
                    ref="upload"
                    :show-file-list="false"
                    action="/index/upload"
                    :before-upload="beforeUpload"
                    :on-change="handleChange"
                    :auto-upload="false"
                    :data="ruleForm">
                <img v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item> -->
        <el-form-item style="text-align:center">
            <el-button type="primary" @click="editsForm(editForm)">确定</el-button>
            <el-button @click="editVisible = false">取消</el-button>
        </el-form-item>
    </el-form>
 
  </el-dialog>
  <!-- 分配 -->
     <el-dialog v-dialogDrag title="分配" :visible.sync="Istributiondialog" width="50%">
      <el-form ref="editform" :model="editform" label-width="70px" class="display">
        <el-form-item label="所属地区：" :label-width="labelwidth" class="wid50">
            <el-select  placeholder="请选择" @change="changevalue">
                <el-option v-for="item in options" :key='item.REGION_ID' :label="item.REGION_NAME" :value="item.REGION_ID" >
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="所属街道：" :label-width="labelwidth" class="wid50">
               <el-select  placeholder="请选择" @change="changecommunitvalue">
                  <el-option v-for="item in optionsstreet" :key='item.STREET_ID' :label="item.STREET_NAME" :value="item.STREET_ID" >
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="所属社区：" :label-width="labelwidth" class="wid50">
                <el-select placeholder="请选择" @change="changeplot">
                  <el-option v-for="item in optionscommunit" :key='item.COMMUNITY_ID' :label="item.COMMUNITY_NAME" :value="item.COMMUNITY_ID" >
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="小区：" :label-width="labelwidth" class="wid50">
                <el-select placeholder="请选择">
                  <el-option v-for="item in optionsplot" :key='item.VILLAGE_ID' :label="item.VILLAGE_NAME" :value="item.VILLAGE_ID" >
                  </el-option>
                </el-select>
            </el-form-item>
      </el-form> 
      <span slot="footer" class="dialog-footer">
                    <el-button @click="Istributiondialog = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
    </el-dialog> 
  </div>
</template>

<script>
import '../../assets/css/common.css'
export default {
  name: 'home',
  data () {
    return {
      currentPage:1, //初始页
      pagesize:10,  
      labelswidth: '160px',
      labelwidth: '120px',
       ruleForm: {
               
            },
            rules: {
                name: [
                    { message: '请输入活动名称', trigger: 'blur'},
                ],
                imageUrl: [
                    { message: '请上传图片', trigger: 'blur'},
                ],
            },
        editForm: '',
        addeditVisible:false,
        editVisible:false,
        detailList:[],
       tableData: [],
       Istributiondialog: false,
       option: [],
       optionsstreet: [],
       optionscommunit: [],
       optionsplot: [],
       imgBroadcastList:[], // 储存旬中的图片列表
         imgsStr: '', // 后端需要的多张图base64字符串，分割
         dialogImageUrl: '',
         diaLogForm: {
           goodsName:'', // 商品名称字段
           imgBroadcastList:[], // 储存选中的图片列表
           imgsStr:''   // 后端需要的多张图base64字符串 , 分割
         },
    }
  },
  created(){
    this.getdata()
    this.getselect()
},
  methods: {
       // 图片选择后 保存在 diaLogForm.imgBroadcastList 对象中
   imgBroadcastChange (file, fileList) {
    //    this.createMiniQrcode(URL.createObjectURL(file.raw)
    const isLt2M = file.size / 1024 / 1024 < 2 // 上传头像图片大小不能超过 2MB
    if (!isLt2M) {
     this.diaLogForm.imgBroadcastList = fileList.filter(v => v.uid !== file.uid)
     this.$message.error('图片选择失败，每张图片大小不能超过 2MB,请重新选择!')
    } else {
        // console.log(URL.createObjectURL(file.raw))
        this.imgsStr = URL.createObjectURL(file.raw)
     this.diaLogForm.imgBroadcastList.push(file)
    //  console.log(this.diaLogForm.imgBroadcastList.push(file))
    //  this.submitDialogData()
    }
   },
   // 有图片移除后 触发
   imgBroadcastRemove (file, fileList) {
    this.diaLogForm.imgBroadcastList = fileList
   },
       async getselect(){
            const { data } = await this.$axios.get(this.$url+'/GetRegionListApi')
            this.option = data.filter(item => {
              return item
            })
        },
        async changevalue(e){
            const { data } =await this.$axios.get(this.$url+'/sreetListsApi?id='+e);
            this.optionsstreet = data.filter(item => {
                return item 
            })

        },
        async changecommunitvalue(e){
            console.log(e)
            const { data } =await this.$axios.get(this.$url+'/communityListsApi?id='+e);
            this.optionscommunit = data.filter(item => {
                // console.log(item)
                return item 
            })

        },
        async changeplot(e){
            console.log(e)
            const { data } =await this.$axios.get(this.$url+'/villageListsApi?id='+e);
            this.optionsplot = data.filter(item => {
                // console.log(item)
                return item 
            })
        },
    //     tirggerFile: function(event) {
    //   let file = event.target.files[0];
    //   console.log(file)
    //   let url = "";
    //   var reader = new FileReader();
    //   reader.readAsDataURL(file);
    //   let that = this;
    //   reader.onload = function(e) {
    //     url = this.result.substring(this.result.indexOf(",") + 1);
    //     that.imgUrl = "data:image/png;base64," + url;
    //     // that.$refs['imgimg'].setAttribute('src','data:image/png;base64,'+url);
    //   };
    // },
    // openImg() {
    //   this.$refs.input.click();
    // },
    update(e){
      let file =e.target.files[0];
      console.log(file)
      let url ='';
      var reader =new FileReader();
      console.log(resder)
      reader.readAsDataURL(file)
    },
    // 获取数据
    getdata(){
      this.$axios({
         url: this.$url+'/GetAllRubbishBoxApi?STREET_ID='+localStorage.getItem('STREET_NO')+'&TYPE' ,
         method: 'get',
      }).then(res=>{
        console.log(res.data)
        this.tableData =Object.assign([],res.data)
      })
    },
  
    getFile(event) {
        this.form.multipartFile = event.target.files[0];
        if(formData.get('multipartFile')){//重新选择图片
            formData.delete('multipartFile');
        }
        formData.append("multipartFile", event.target.files[0]);
        
    },
    //新增
    addForms(addForm){
      console.log(addForm)
      this.$axios({
                url: this.$url+'/AddRubbishBoxApi',
                method: 'post',
                data:{
                    name: addForm.NAME,
                    VillageNo: addForm.VillageNo,
                    lng: addForm.LONGITUDE,                      
                    lat: addForm.LATITUDE,
                    size: addForm.SIZE,
                    photo: addForm.photo
                }
            }).then(item=>{
              console.log(item)
               if(item.status == 200){
                  console.log(item.data)
                  this.$message.success('编辑成功')
                  this.communitydetaildata = Object.assign([],item.data)
               }
                
            })
    },
    // 新增弹出框
    addvialog(){
      this.addeditVisible = true
    },
    resetForm(){
      this.addeditVisible = false
    },
    handleEdit(index, row) {
      console.log(row)
            this.editForm = Object.assign({},row)
            // this.editform = row;
            this.editVisible = true;
        },
        // 编辑
    editsForm(form){
        console.log({
            ID: form.ID,
            name: form.NAME,
            VillageNo: form.VILLAGE_NO,
            lng: form.LONGITUDE,
            lat: form.LATITUDE,
            size: form.SIZE,
            photo: form.PHOTO
          })
        this.$axios({
          url: this.$url+'/UpdateRubbishBoxApi',
          method: 'get',
          params:{
            ID: form.ID,
            name: form.NAME,
            VillageNo: form.VILLAGE_NO,
            lng: form.LONGITUDE,
            lat: form.LATITUDE,
            size: form.SIZE,
            photo: form.PHOTO
          }
        }).then(res=>{
          console.log(res)
          if(res.data.IsSucess){
            this.editVisible = false;
            this.$message.success('编辑成功')
            this.getdata()
          }
        })
    },
    //删除
    handleDelete(row,index){
      console.log(row)
       this.$confirm('确定删除', '提示', {
                type: 'warning'
            })
                .then(() => {
                  this.$axios({
                    url: this.$url+'/DeleteRubbishBoxApi',
                    method:'get',
                    params:{
                      ID: row.ID
                    }
                  }).then(res=>{
                    console.log(res)
                    this.$message.success('删除成功');
                    this.getdata()
                  })
                    // this.$message.success('删除成功');
                    // this.tableData.splice(index, 1);
                })
                .catch(() => {});


    },
    // 分配弹框 
    handledIstribution(index,row){
      this.Istributiondialog = true
    },
    tirggerFile(event){

    },
    // 分页导航
    handlePageChange(currentPage) {
        this.currentPage = currentPage;
        // this.$set(this.query, 'pageIndex', val);
        // this.getData();
    },
    handleSizeChange(size){
        this.pagesize = size;
    },
    // ----------以下为导入Excel数据功能--------------
   // 文件选择回调
   onChange(file, fileList) {
    //  console.log(fileList);
     this.fileData = file; // 保存当前选择文件
     this.readExcel(); // 调用读取数据的方法
   },
   // 读取数据
   readExcel(e) {
     let that = this;
     const files = that.fileData;
    //  console.log(files);
     if (!files) {
       //如果没有文件
       return false;
     } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
       this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
       return false;
     }
     const fileReader = new FileReader();
    //  console.log(fileReader)
     fileReader.onload = ev => {
       try {
         const data = ev.target.result;
        //  console.log(ev.target)
        //  console.log(this);
         const workbook = this.XLSX.read(data, {
           type: "binary"
         });
         if (workbook.SheetNames.length >= 1) {
           this.$message({
             message: "导入数据表格成功",
             showClose: true,
             type: "success"
           });
         }
         const wsname = workbook.SheetNames[0]; //取第一张表
         const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
         this.$axios({
           url:this.$url +'/ImportRubbishBoxApi' ,
           method:'post',
           data: ws
         }).then(res=>{
           console.log(res)
         })
         console.log(ws)
         that.outputs = []; //清空接收数据
         for (var i = 0; i < ws.length; i++) {
           var sheetData = {
             // 键名为绑定 el 表格的关键字，值则是 ws[i][对应表头名]
            //  ID: ws[i]["ID"],
             VILLAGE_NAME: ws[i]["VILLAGE_NAME"],
             NAME: ws[i]["NAME"],
             AREA: ws[i]["AREA"],
             LONGITUDE: ws[i]["LONGITUDE"],
             LATITUDE: ws[i]["LATITUDE"],
             LOCATION: ws[i]["LOCATION"],
            //  WEIGHT_YH: ws[i]['重量'],
             SIZE: ws[i]["SIZE"],
             PHOTO: ws[i]['PHOTO'],
             REMARK: ws[i]['REMARK'],
           };
           that.tableData.unshift(sheetData);
         }
         
         this.$refs.upload.value = "";
       } catch (e) {
         return false;
       }
     };
     // 如果为原生 input 则应是 files[0]
     fileReader.readAsBinaryString(files.raw);
   },
   exportToExcel(){
     require.ensure([],()=>{
       const {export_json_to_excel} = require('../../excel/export2Excel');
       const tHeader = ['VILLAGE_NAME','NAME', 'AREA','LONGITUDE','LATITUDE','LOCATION','WEIGHT_YH','SIZE','PHOTO','REMARK'];
       const filterVal = ['VILLAGE_NAME','NAME','AREA','LONGITUDE','LATITUDE','LOCATION','WEIGHT_YH','SIZE','PHOTO','REMARK'];
       const list = this.tableData;
       const data = this.formatJson(filterVal, list);
       export_json_to_excel(tHeader, data, "垃圾桶信息列表");
     });
   },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    submitForm(formName) {
      console.log(formName)
                let vm = this;
                
            },
            handleChange (file, fileList) {
                this.ruleForm.imageUrl = URL.createObjectURL(file.raw);
            },
 
            beforeUpload(file) {
                return true;
            },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.container{
  width: 100%;
  height: 100%;
}
.wid50{
  width: 50%;
}
.flex{
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    padding:0 5px;
}
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
    }
    .el-select{
      width: 100%;
    }
    /deep/.el-upload__input{
      display: none!important;
    }
</style>
